package com.mandao.oneplat.boot.handler;

import com.mandao.oneplat.boot.OnePlatConfig;
import com.mandao.oneplat.boot.context.OneContext;
import com.mandao.oneplat.boot.context.OneResponse;
import com.mandao.oneplat.boot.mvc.control.EOneCOntrolUriMode;
import com.mandao.oneplat.boot.mvc.view.OneView;
import com.mandao.oneplat.boot.mvc.view.OneViewResolver;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import org.json.simple.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by sunson on 2017/3/21.
 */
public class OneServerViewHandler extends ChannelOutboundHandlerAdapter {

    private OnePlatConfig oneOption;
    private OneViewResolver oneViewResolver;

    public OneServerViewHandler(OneViewResolver oneViewResolver, OnePlatConfig oneOption) {
        this.oneOption = oneOption;
        this.oneViewResolver = oneViewResolver;
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof OneContext) {
            OneContext oneContext = (OneContext) msg;
            if (oneContext.getOneResponse() != null && oneContext.getOneResponse().getHttpResponse() != null) {
                ctx.write(oneContext);
                return;
            }
            // 需要处理View
            OneView oneView = oneContext.getOneView();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Writer contentWriter = new OutputStreamWriter(bos);
            if (EOneCOntrolUriMode.HTML == oneView.getUriMode()) {
                if (oneView.getViewName().equals("502")) {
                    contentWriter.write("Server Internal Error.[502]");
                    contentWriter.flush();
                } else {
                    oneViewResolver.revoleThemeView(oneContext, contentWriter);
                }
            } else if (EOneCOntrolUriMode.JSON == oneView.getUriMode()) {
                contentWriter.write(JSONObject.toJSONString(oneContext.getOneModel().getModels()));
                contentWriter.flush();
            } else if (EOneCOntrolUriMode.STATIC == oneView.getUriMode()) {
                oneViewResolver.resolveAssetsView(oneContext, contentWriter);
            }
            if (bos.size() <= 0) {
                oneContext.getOneResponse().setHttpResponse(OneResponse.BAD_RESPONSE);
            } else {
                oneContext.getOneResponse().setHttpResponse(new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bos.toByteArray())));
            }
            ctx.write(oneContext);
        }
    }
}
